import Koa from 'koa'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import { Sequelize,DataTypes,Op } from 'sequelize'
import cors from '@koa/cors'

let app = new Koa()
let router = new Router()

// 创建sequelize实例
const sequelize = new Sequelize('bookdb','root','123456',{
    dialect:'mysql',
    host:'localhost'
})
// 创建数据库实例，连接数据库
const Book = sequelize.define('book',{
    bookName: DataTypes.STRING,
    author: DataTypes.STRING
})

// await sequelize.sync({force:true})

// // 初始数据
// await Book.bulkCreate([
//     {
//         bookName: 'vue3前端开发框架应用',
//         author: '董宁',

//     },
//     {
//         bookName: '围城',
//         author: '钱中书'
//     }
// ])

router.use(bodyParser())

router.get('/book', async (ctx) => {
    let keyword = ctx.request.query.keyword || ''
    let books ;
    if(keyword){
        books = await Book.findAll({
            where: {
                [Op.or]:{
                    bookName:{
                        [Op.like]: `%${keyword}%`
                    },
                    author:{
                        [Op.like]: `%${keyword}%`
                    },
                }
            }
        })
    }else{
        books = await Book.findAll()
    }
    ctx.body = {
        code:1000,
        data:books,
        msg:'查询成功'
    }
})
router.get('/book/:id', async (ctx) => {
    let id = ctx.params.id || 0
    let book = await Book.findByPk(id)
    ctx.body = {
        code:1000,
        data:book,
        msg:'查询单个成功'
    }
})

router.post('/book', async (ctx) => {
    let obj = ctx.request.body || ''
    console.log(obj);
    
    let book = await Book.create(obj)
    ctx.body = {
        code:1000,
        data:book,
        msg:'新增成功'
    }
})
router.put('/book/:id', async (ctx) => {
    let id = ctx.params.id || 0
    let book = await Book.findByPk(id)
    if(book){
        let obj = ctx.request.body
        let newBook = await Book.update(obj,{ where :{id}})
        ctx.body =  {
            code:1000,
            data:newBook,
            msg:'修改成功'
        }
    }
    
})
router.delete('/book/:id', async (ctx) => {
    let id = ctx.params.id || 0
    let book = await Book.findByPk(id)
    if(book){
        let obj = await Book.destroy({ where :{id}})
        ctx.body =  {
            code:1000,
            data:obj,
            msg:'删除成功'
        }
    }
})

app.use(cors())
app.use(router.routes())

app.listen(3000)

console.log('该项目运行在如下地址：http://localhost:3000');


